"""
Created on 30-Nov-2009

@author: dexen
"""

import sys
import time
from threading import Lock
import multiprocessing as mp

import rpyc
from rpyc.utils import server

import dexen
from dexen.system.common import service
from dexen.system.common.service import DexenAddr
from dexen.system.registry.core import RegistryCore

#===============================================================================
# Globals
#===============================================================================
core = RegistryCore()
lock = Lock()


#===============================================================================
# Service Class
#===============================================================================
class RegistryService(dexen.Service): 
    def on_disconnect(self):
        print "I am disconnected"
            
    def on_connect(self):
        print "I am connected"
    
    def register_server(self, stime, addr):
        addr = rpyc.classic.obtain(addr)
        assert isinstance(addr, DexenAddr)
        core.register_server(addr)
        
    def get_server_addr(self):
        return core.get_server_addr()
        
    def register_node(self, stime, addr):
        with lock:
            addr = rpyc.classic.obtain(addr)
            assert isinstance(addr, DexenAddr)
            return core.register_node(addr)
    
    def get_new_nodes(self):
        with lock:
            return core.get_new_nodes()
    
    def register_master(self, name, addr):
        with lock:
            addr = rpyc.classic.obtain(addr)
            assert isinstance(addr, DexenAddr)
            core.register_master(name, addr)
            
    def get_master_addr(self, name):
        with lock:
            return core.get_master_addr(name)
    
    def register_slave(self, name, addr):
        with lock:
            addr = rpyc.classic.obtain(addr)
            assert isinstance(addr, DexenAddr)
            core.register_slave(name, addr)
            
    def get_slave_addr(self, name):
        with lock:
            return core.get_slave_addr(name)
            

def _start_rpyc():
    sys.argv = ["blahblah"]
    import rpyc_reg_service # this starts the registry 
    
def start(name="dexen_server"):
    p = mp.Process(target=_start_rpyc)
    p.daemon = True
    p.start()
    time.sleep(1)
    RegistryService.ALIASES = [name]
    svr = server.ThreadedServer(RegistryService, 
                                port=service.REGISTRY_PORT,
                                protocol_config=service.default_config)
    svr.start()

    
#===============================================================================
# Main
#===============================================================================
def main():
    pass

if __name__ == "__main__":
    main()
